//
//  JDMyCommissionViewController.swift
//  DragonWallet
//
//  Created by volantPig on 2024/11/10.
//

import UIKit
import PGDatePicker
// 我的推广提成  我的现金账目
class JDMyCommissionViewController: JDBaseViewController {

    var headerContainerView: UIView?
    var walletNumberLabel: UILabel?
    
    var bottomContainerView: UIView?
    var extractButton: UIButton?
    
    var mainTableView: UITableView?
    var dataSource: [[String]]?
    
    var yearMonthButton: UIButton?
    
    var currentDateComponents: DateComponents?
    
    var recordModels: [JDPromotionCommissionRecordModel?]?
    
    var balanceModel: JDBalanceModel?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.setupConfig()
        self.setupUIElements()
        self.fetchUserBalance()
        self.getNetData()
        // Do any additional setup after loading the view.
    }
    
    func setupConfig() {
        self.setupNavigationTitle("我的现金账目")
        self.setupLeftBackItem()
        self.dataSource = [["aaaa"],["bbbb"],["cccc"]]
    }
    
    func setupUIElements() {
        
        self.bottomContainerView = UIView()
        self.view.addSubview(self.bottomContainerView!)
        self.bottomContainerView?.snp.makeConstraints({ make in
            make.leading.trailing.equalTo(self.view)
            make.bottom.equalTo(self.view)
            make.height.equalTo(bottomSaftAreaHeight+50+14)
        })
        self.bottomContainerView?.backgroundColor = .white
        
        self.extractButton = UIButton(type: .system)
        self.bottomContainerView?.addSubview(self.extractButton!)
        self.extractButton?.snp.makeConstraints({ make in
            make.leading.equalTo(self.bottomContainerView!).offset(12)
            make.trailing.equalTo(self.bottomContainerView!).offset(-12)
            make.top.equalTo(self.bottomContainerView!).offset(14)
            make.height.equalTo(50)
        })
        self.extractButton?.makeCorner(25)
        self.extractButton?.buttonConfig(normalTitle: "去提现", normalTitleColor: .white, titleFont: UIFont.systemFont(ofSize: 16, weight: .regular), backgroundColor: color("#FA6161"))
        self.extractButton?.addTarget(self, action: #selector(extractButtonAction), for: .touchUpInside)
        
        self.mainTableView = UITableView(frame: .zero, style: .plain)
        self.view.addSubview(self.mainTableView!)
        self.mainTableView?.snp.makeConstraints({ make in
            make.leading.trailing.equalTo(self.view)
            make.top.equalTo(self.view).offset(statusBarHeight+44)
            make.bottom.equalTo(self.bottomContainerView!.snp.top).offset(-10)
        })
        self.mainTableView?.separatorStyle = .none
        self.mainTableView?.delegate = self
        self.mainTableView?.dataSource = self
        self.mainTableView?.register(UITableViewCell.self, forCellReuseIdentifier: "myCell")
        self.mainTableView?.register(UITableViewHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: "headerView")
        self.mainTableView?.backgroundColor = .commonColor()
//
////        if #available(iOS 15.0, *) {
////            self.mainTableView?.sectionHeaderTopPadding = .zero
////        } else {
////            // Fallback on earlier versions
////        }
////        self.mainTableView?.contentInsetAdjustmentBehavior = .never
//        
//        
//        let headerView = self.createHeaderView()
//        headerView.frame = CGRectMake(0, -156, screenWidth, 156)
//        self.mainTableView?.addSubview(headerView)
        self.mainTableView?.tableHeaderView = self.createHeaderView()
        
        self.mainTableView?.addRefreshHeader(ignoredTopInset: 0, { [weak self] in
            self?.currentPage = 1
            self?.getNetData()
            self?.fetchUserBalance()
        })
        
        self.mainTableView?.addRefreshFooter { [weak self] in
            self?.currentPage += 1
            self?.getNetData(false )
        }
        
    }
    
    func createHeaderView() -> UIView {
        
        let baseContainerView = UIView()
        baseContainerView.frame = CGRectMake(0, 0, screenWidth, 136+20)
        baseContainerView.backgroundColor = .commonColor()
        
        self.headerContainerView = UIView()
        baseContainerView.addSubview(self.headerContainerView!)
        self.headerContainerView?.snp.makeConstraints({ make in
            make.leading.equalTo(baseContainerView).offset(12)
            make.trailing.equalTo(baseContainerView).offset(-12)
            make.top.equalTo(baseContainerView).offset(10)//.offset(statusBarHeight+44)
            make.height.equalTo(136)
        })
        self.headerContainerView?.backgroundColor = .white
        self.headerContainerView?.makeCorner(8)
        
        let walletTitle = UILabel()
        self.headerContainerView?.addSubview(walletTitle)
        walletTitle.snp.makeConstraints { make in
            make.centerX.equalTo(self.headerContainerView!)
            make.top.equalTo(self.headerContainerView!).offset(20)
            make.height.equalTo(20)
        }
        walletTitle.text = "可提现金额"
        walletTitle.labelConfig(textAlignment: .center, font: UIFont.systemFont(ofSize: 14, weight: .regular), textColor: color("#333333"), numberOfLines: 1)
        
        
        self.walletNumberLabel = UILabel()
        self.headerContainerView?.addSubview(self.walletNumberLabel!)
        self.walletNumberLabel?.snp.makeConstraints({ make in
            make.height.equalTo(45)
            make.top.equalTo(walletTitle.snp.bottom).offset(6)
            make.centerX.equalTo(self.headerContainerView!)
        })
        self.walletNumberLabel?.labelConfig(textAlignment: .center, font: UIFont.systemFont(ofSize: 32, weight: .semibold), textColor: color("#333333"), numberOfLines: 1)
        self.walletNumberLabel?.text = "￥50.00"
        self.walletNumberLabel?.priceString(UIFont.systemFont(ofSize: 16, weight: .semibold), UIFont.systemFont(ofSize: 32, weight: .semibold))
        
        let walletDescriptionLabel = UILabel()
        self.headerContainerView?.addSubview(walletDescriptionLabel)
        walletDescriptionLabel.snp.makeConstraints { make in
            make.centerX.equalTo(self.headerContainerView!)
            make.top.equalTo(self.walletNumberLabel!.snp.bottom).offset(5)
            make.height.equalTo(20)
        }
        walletDescriptionLabel.text = " 平台单笔提现金额>=￥25"
        walletDescriptionLabel.labelConfig(textAlignment: .center, font: UIFont.systemFont(ofSize: 14, weight: .regular), textColor: color("#9DA1B2"), numberOfLines: 1)
        walletDescriptionLabel.appendImgV("hint_alert", at: 0)
        
        return baseContainerView
    }
    
    /// 获取用户账户余额，可提现金额
    func fetchUserBalance() {
        JDNetWorkRequest(.fetchUserBalance([:])) { responseStr in
            
            print("这里的返回:\(responseStr)")
            
            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
                
//                JDBalanceModel
                
                if let balanceModel = JDBalanceModel.deserialize(from: responseStr, designatedPath: "data") {
                    
                    self.balanceModel = balanceModel
                    
                    self.walletNumberLabel?.text = String(format: "￥%@", balanceModel.balanceText ?? "0.00")
                    self.walletNumberLabel?.priceString(UIFont.systemFont(ofSize: 16, weight: .semibold), UIFont.systemFont(ofSize: 32, weight: .semibold))
                    
                }                
            }
            
        } failure: { error in
            
        } error: { errorCode in
            
        }

    }
    
    
    
    override func getNetData(_ isRefresh: Bool = true) {
                
        var params = [String: Any]()
        params["pageNumber"] = self.currentPage
        params["pageSize"] = 10
        params["year"] = self.currentDateComponents?.year ?? Date.currentYear()
        params["month"] = self.currentDateComponents?.month ?? Date.currentMonth()
        
        self.showLoading()
        JDNetWorkRequest(.pageUserPromotionCommission(params)) { responseStr in
            self.dismissLoading()
            print("收益记录结果:\(responseStr)")
            
            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
                
//                {"msg":"ok","data":{"records":[{"commissionTypeString":"提现","mobile":"13998463668","nickname":"手机用户3668","promotionCommission":"1.20","downLineUserId":-1,"promotionTime":""}],"pageNumber":1,"totalRow":1,"pageSize":10,"totalPage":1},"code":0}
                
                if let models = [JDPromotionCommissionRecordModel].deserialize(from: responseStr, designatedPath: "data.records") {
                    if isRefresh {
                        self.recordModels = models
                    } else {
                        self.recordModels?.append(contentsOf: models)
                    }
                }
//                updateCompleted(JSON(commonModel?.data ?? [:]).dictionary)
//                commonModel?.data
            }
//            JDPromotionCommissionModel
            self.mainTableView?.reloadData()
            self.mainTableView?.endRefresh()
        } failure: { error in
            self.dismissLoading()
            self.mainTableView?.endRefresh()
        } error: { errorCode in
            self.dismissLoading()
            self.mainTableView?.endRefresh()
        }

    }
    
    @objc func extractButtonAction() {
        let extractVC = JDExtractViewController()
        extractVC.balanceModel = self.balanceModel
        extractVC.cashOutCompleted = { [weak self] in
            self?.fetchUserBalance()
            self?.getNetData(true)
        }
        self.hidesBottomBarPushViewController(extractVC)
    }
    
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

extension JDMyCommissionViewController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.recordModels?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "myCell")
        
        for subV in cell?.contentView.subviews ?? [UIView]() {
            subV.removeFromSuperview()
        }
        
//        {"msg":"ok","data":{"records":[{"commissionTypeString":"提现","mobile":"13998463668","nickname":"手机用户3668","promotionCommission":"1.20","downLineUserId":-1,"promotionTime":""}],"pageNumber":1,"totalRow":1,"pageSize":10,"totalPage":1},"code":0}
        
        let currentModel = self.recordModels?[indexPath.row]
        

        cell?.contentView.backgroundColor = .commonColor()
        
        let containerView = UIView()
        cell?.contentView.addSubview(containerView)
        containerView.snp.makeConstraints { make in
            make.leading.equalTo(cell!.contentView).offset(12)
            make.trailing.equalTo(cell!.contentView).offset(-12)
            make.top.equalTo(cell!.contentView)
            make.bottom.equalTo(cell!.contentView)//.offset(-10)
        }
        containerView.backgroundColor = .white
        containerView.makeCorner(8)
        
        let titleLabel = UILabel()
        containerView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.leading.equalTo(containerView).offset(12)
            make.top.equalTo(containerView).offset(17)
            make.height.equalTo(17)
        }
        titleLabel.text = currentModel?.commissionTypeString
        titleLabel.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 12, weight: .regular), textColor: color("#9DA1B2"))
        
        let nameLabel = UILabel()
        containerView.addSubview(nameLabel)
        nameLabel.snp.makeConstraints { make in
            make.leading.equalTo(containerView).offset(12)
            make.top.equalTo(titleLabel.snp.bottom).offset(2)
            make.height.equalTo(22)
        }
        nameLabel.text = currentModel?.nickname
        nameLabel.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 16, weight: .regular), textColor: color("#333333"))
        
//        {"msg":"ok","data":{"records":[{"commissionTypeString":"提现","mobile":"13998463668","nickname":"手机用户3668","promotionCommission":"1.20","downLineUserId":-1,"promotionTime":""}],"pageNumber":1,"totalRow":1,"pageSize":10,"totalPage":1},"code":0}
        
        
        let timeLabel = UILabel()
        containerView.addSubview(timeLabel)
        timeLabel.snp.makeConstraints { make in
            make.trailing.equalTo(containerView).offset(-12)
            make.centerY.equalTo(titleLabel)
        }
        timeLabel.text = currentModel?.promotionTime ?? "数据为空"
        timeLabel.labelConfig(textAlignment: .right, font: UIFont.systemFont(ofSize: 12, weight: .regular), textColor: color("#333333"))
        
        let priceLabel = UILabel()
        containerView.addSubview(priceLabel)
        priceLabel.snp.makeConstraints { make in
            make.trailing.equalTo(containerView).offset(-12)
            make.centerY.equalTo(nameLabel)
        }
        priceLabel.labelConfig(textAlignment: .right, font: UIFont.systemFont(ofSize: 12, weight: .semibold), textColor: color("#FA6161"))
        
        if currentModel?.commissionTypeString == "推广" || currentModel?.commissionTypeString == "提成" {
            priceLabel.text = String(format: "+￥%@", currentModel?.promotionCommission ?? "")
            priceLabel.textColor = color("#FA6161")
        } else {
            priceLabel.text = String(format: "-￥%@", currentModel?.promotionCommission ?? "")
            priceLabel.textColor = color("#333333")
        }
//        if currentModel?.commissionTypeString == "提现" {
//            priceLabel.text = String(format: "-￥%@", currentModel?.promotionCommission ?? "")
//        }  else if currentModel?.commissionTypeString == "提成" {
//            priceLabel.text = String(format: "+￥%@", currentModel?.promotionCommission ?? "")
//        } else {
//            priceLabel.text = String(format: "￥%@", currentModel?.promotionCommission ?? "")
//        }
        
        let line = UIView()
        containerView.addSubview(line)
        line.snp.makeConstraints { make in
            make.leading.equalTo(containerView).offset(12)
            make.trailing.equalTo(containerView).offset(-12)
            make.height.equalTo(1)
            make.bottom.equalTo(containerView)
        }
        line.backgroundColor = .commonColor()
        
        
        return cell!
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 81
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0 {
            return 64
        }
        return 0.001
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        if section == 0 {
            let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "headerView")
            
            for subV in headerView?.contentView.subviews ?? [UIView]() {
                subV.removeFromSuperview()
            }
            
            let containerView = UIView()
            headerView?.contentView.addSubview(containerView)
            containerView.snp.makeConstraints { make in
                make.leading.equalTo(headerView!.contentView).offset(12)
                make.trailing.equalTo(headerView!.contentView).offset(-12)
                make.top.equalTo(headerView!.contentView)
                make.bottom.equalTo(headerView!.contentView)
            }
//            containerView.makeBezierPathCorner([.topLeft,.topRight], 8)
            containerView.backgroundColor = .white
            
            let headerTitleLabel = UILabel()
            containerView.addSubview(headerTitleLabel)
            headerTitleLabel.snp.makeConstraints { make in
                make.leading.equalTo(containerView).offset(12)
                make.bottom.equalTo(containerView.snp.centerY).offset(0)
                make.height.equalTo(20)
            }
            headerTitleLabel.text = "余额变更明细"
            headerTitleLabel.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 14, weight: .regular), textColor: color("#333333"), numberOfLines: 1)
            
            self.yearMonthButton = UIButton(type: .custom)
            containerView.addSubview(self.yearMonthButton!)
            self.yearMonthButton?.snp.makeConstraints { make in
                make.leading.equalTo(containerView).offset(12)
                make.top.equalTo(containerView.snp.centerY).offset(0)
                make.height.equalTo(20)
            }
            self.yearMonthButton?.buttonConfig(normalTitle: "", normalImageNamed: "", normalTitleColor: color("#333333"), titleFont: UIFont.systemFont(ofSize: 13, weight: .semibold), backgroundColor: .white)
            if self.currentDateComponents == nil {
                self.yearMonthButton?.setAttributedTitle(String(format: "%@年%@月", Date.currentYear(),Date.currentMonth()).appendImgV("arrow_down"), for: .normal)
            } else {
                self.yearMonthButton?.setAttributedTitle(String(format: "%d年%d月", self.currentDateComponents?.year ?? 1970 ,self.currentDateComponents?.month ?? 1).appendImgV("arrow_down"), for: .normal)
            }
            
            
            self.yearMonthButton?.addTarget(self, action: #selector(yearMonthButtonAction(_:)), for: .touchUpInside)
            
            
            // 收入
            let incomeLabel = UILabel()
            containerView.addSubview(incomeLabel)
            incomeLabel.snp.makeConstraints { make in
                make.trailing.equalTo(containerView).offset(-12)
                make.centerY.equalTo(headerTitleLabel)
            }
            incomeLabel.text = "收入:+￥122.00"
            incomeLabel.labelConfig(textAlignment: .right, font: UIFont.systemFont(ofSize: 12, weight: .regular), textColor: color("#FA6161"))
            incomeLabel.isHidden = true
            
            // 提现
            let extractLabel = UILabel()
            containerView.addSubview(extractLabel)
            extractLabel.snp.makeConstraints { make in
                make.trailing.equalTo(containerView).offset(-12)
                make.centerY.equalTo(self.yearMonthButton!)
            }
            extractLabel.text = "提现:-￥122.00"
            extractLabel.labelConfig(textAlignment: .right, font: UIFont.systemFont(ofSize: 12, weight: .regular), textColor: color("#333333"))
            extractLabel.isHidden = true
            
            let line = UIView()
            headerView?.contentView.addSubview(line)
            line.snp.makeConstraints { make in
                make.leading.equalTo(headerView!.contentView).offset(12)
                make.trailing.equalTo(headerView!.contentView).offset(-12)
                make.bottom.equalTo(headerView!.contentView)
                make.height.equalTo(1)
            }
            line.backgroundColor = .commonColor()
            
            
            return headerView
        } else {
            return nil
        }
        
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.001
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
    
    @objc func yearMonthButtonAction(_ button: UIButton) {
        
        let datePickerManager = PGDatePickManager()
        datePickerManager.isShadeBackground = true
        datePickerManager.style = .sheet //.alertBottomButton
        let datePicker = datePickerManager.datePicker!
        datePicker.delegate = self
        datePicker.datePickerType = .line
        datePicker.datePickerMode = .yearAndMonth
        self.present(datePickerManager, animated: false, completion: nil)
        
    }
    
}

extension JDMyCommissionViewController: PGDatePickerDelegate {
    func datePicker(_ datePicker: PGDatePicker!, didSelectDate dateComponents: DateComponents!) {
        print("dateComponents = ", dateComponents)
        self.currentDateComponents = dateComponents
        let yearMonthStr = String.init(format: "%zd年%zd月", dateComponents.year ?? 0, dateComponents.month ?? 0)
        self.yearMonthButton?.setAttributedTitle(yearMonthStr.appendImgV("arrow_down"), for: .normal)
        self.getNetData(true)
    }
}
